<template>
  <div class="add_con_form tl" v-loading="loading">
    <el-dialog
      :close-on-click-modal="false"
      :title="mytitle"
      :modal-append-to-body="false"
      :visible.sync="visible"
      :show="show"
      :before-close="closeDialog"
      @close="$emit('update:show', false)"
      class="tl size_13"
      width="800px"
    >
      <el-form
        :model="data"
        :rules="dataYZ"
        ref="data"
        class="mar_top"
        label-width="200px"
      >
        <el-form-item>
          <el-col :span="24">温馨提示：空或者0为不限制</el-col>
        </el-form-item>

        <el-form-item label="红包名称" prop="title">
          <el-col :span="12">
            <el-input placeholder v-model="data.title" clearable></el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="红包类型" prop="pay_types">
          <el-col :span="16">
            <el-radio-group
              v-model="data.types"
              @change="
                data.jf_change = 0;
                data.cdn_pid = 0;
                data.cdn_sid = 0;
              "
            >
              <el-radio label="0">商城红包</el-radio>
              <el-radio
                label="1"
                v-if="
                  $store.state.plugin.djpt &&
                  $store.state.plugin.djpt.is_open == 1
                "
              >
                代驾红包
              </el-radio>
              <el-radio
                label="2"
                v-if="
                  ($store.state.plugin.gxgd &&
                    $store.state.plugin.gxgd.is_open == 1) ||
                  ($store.state.plugin.qyyy &&
                    $store.state.plugin.qyyy.is_open == 1)
                "
              >
                权益红包
              </el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>

        <el-form-item label="领取类型" prop="pay_types">
          <el-col :span="16">
            <el-radio-group
              v-model="data.pay_types"
              @change="data.jf_change = 0"
            >
              <el-radio label="0">普通红包</el-radio>
              <el-radio label="1">需积分可兑换</el-radio>
              <el-radio label="2">需余额可兑换</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>

        <el-form-item label="红包金额" prop="money">
          <el-col :span="12">
            <el-input
              placeholder
              v-model="data.money"
              v-Int
              type="text"
              clearable
            ></el-input>
          </el-col>
          <el-col :span="3">&nbsp;元</el-col>
        </el-form-item>

        <el-form-item label="累计消费满" prop="cdn_xfm">
          <el-col :span="12">
            <el-input
              v-Int
              placeholder
              v-model.number="data.cdn_xfm"
              clearable
            ></el-input>
          </el-col>
          <el-col :span="3">&nbsp;元可使用</el-col>
        </el-form-item>

        <el-form-item
          label="多少积分兑换一张"
          prop="jf_change"
          v-if="data.pay_types == 1"
        >
          <el-col :span="12">
            <el-input
              placeholder
              v-enterNumber
              type="text"
              v-model.number="data.jf_change"
              clearable
            ></el-input>
          </el-col>
          <el-col :span="3">&nbsp;积分</el-col>
        </el-form-item>

        <el-form-item
          label="多少金额购买一张"
          prop="jf_change"
          v-if="data.pay_types == 2"
        >
          <el-col :span="12">
            <el-input
              placeholder
              v-enterNumber
              type="text"
              v-model.number="data.jf_change"
              clearable
            ></el-input>
          </el-col>
          <el-col :span="3">&nbsp;元</el-col>
        </el-form-item>

        <el-form-item
          label="是否免费领取"
          prop="page_get"
          v-if="data.pay_types == 0"
        >
          <el-col :span="20">
            <el-radio-group v-model="data.page_get">
              <el-radio label="0">是</el-radio>
              <el-radio label="1">否</el-radio>
            </el-radio-group>
          </el-col>
          <el-col :span="24" style="font-size: 14px; line-height: 1.6">
            PS：<span style="color: red">是</span>，则用户可以在<span
              style="color: red"
              >商品详情</span
            >页面和<span style="color: red">我的红包</span>页面中领取红包。
            <br />
            <span style="color: red">否</span>，则该红包为<span
              style="color: red"
              >活动红包</span
            >，需要在<span style="color: red">指定的场景</span>中领取，
            <br />
            商品详情页面和我的红包页面中<span style="color: red"
              >不可领取该红包</span
            >。
          </el-col>
        </el-form-item>

        <el-form-item
          label="指定商品ID"
          prop="cdn_pid"
          v-if="data.types == 0 || data.types == 2"
        >
          <el-col :span="14">
            <div v-if="data.cdn_pid == '0'">
              <div>
                <el-tag type="success">应用所有商品</el-tag>
              </div>
            </div>
            <div
              v-else-if="data.cdn_pid"
              style="display: flex; flex-wrap: wrap"
            >
              <div v-for="(item, i) in data.cdn_pid.split(',')" :key="i">
                <el-tag
                  type="success"
                  style="margin-right: 10px"
                  closable
                  @close="handleClose(item, i)"
                  >{{ "id：" + item }}</el-tag
                >
              </div>
            </div>
            <el-button
              :loading="$store.state.isLoading"
              size="small"
              type="primary"
              @click="xzshop('xzShop')"
              >选择商品</el-button
            >
          </el-col>
        </el-form-item>

        <el-form-item label="指定商家ID" prop="cdn_sid" v-if="data.types == 0">
          <el-col :span="12">
            <div>
              <div>
                <el-tag type="success">{{
                  data.cdn_sid == "0" || data.cdn_sid == ""
                    ? "自营"
                    : "id：" + data.cdn_sid
                }}</el-tag>
              </div>
            </div>
            <el-button
              :loading="$store.state.isLoading"
              size="small"
              type="primary"
              @click="xzshop('xzusershop')"
              >选择商家</el-button
            >
            <el-button
              :loading="$store.state.isLoading"
              size="small"
              type="warning"
              @click="data.cdn_sid = 0"
              >自营</el-button
            >
          </el-col>
          <el-col :span="20" style="font-size: 14px; line-height: 1.6">
            PS：选择指定供应商，则该红包仅供应商的商品可使用，如果不选则只能自营的商品使用。
          </el-col>
        </el-form-item>
        <el-form-item
          label="指定代理商ID"
          prop="cdn_sid"
          v-if="data.types == 1"
        >
          <el-col :span="12">
            <div v-if="data.cdn_sid != ''">
              <div>
                <el-tag type="success">{{
                  data.cdn_sid == "0" ? "应用所有代理商" : "id：" + data.cdn_sid
                }}</el-tag>
              </div>
            </div>
            <el-button
              :loading="$store.state.isLoading"
              size="medium"
              type="primary"
              @click="xzshop('xzdriverwork')"
              >选择代理商</el-button
            >
          </el-col>
        </el-form-item>

        <el-form-item
          label="指定商品分类"
          prop="cdn_pid"
          v-if="data.types == 0 || data.types == 2"
        >
          <el-col :span="14">
            <div v-if="data.cdn_cid_cn" style="display: flex; flex-wrap: wrap">
              <div v-for="(item, i) in data.cdn_cid_cn" :key="i">
                <el-tag
                  type="success"
                  style="margin-right: 10px"
                  closable
                  @close="handleCloses(i)"
                  >{{ item.title }}</el-tag
                >
              </div>
            </div>
            <el-button
              :loading="$store.state.isLoading"
              size="small"
              type="primary"
              @click="xzshop('xzShopCate')"
              >选择商品分类</el-button
            >
          </el-col>
          <el-col :span="20" style="font-size: 14px; line-height: 1.6">
            PS：指定商品分类，则该红包仅该分类下的商品可使用；如果同时指定了商品ID，则以指定商品ID优先，指定商品分类失效。
          </el-col>
        </el-form-item>

        <el-form-item label="领取后多久过期" prop="lifetime">
          <el-col :span="12">
            <el-input
              placeholder
              v-enterNumber
              type="text"
              v-model.number="data.lifetime"
              clearable
            ></el-input>
          </el-col>
          <el-col :span="3">&nbsp;天</el-col>
        </el-form-item>

        <el-form-item label="每人限量" prop="limit_num">
          <el-col :span="12">
            <el-input
              placeholder
              v-enterNumber
              type="text"
              v-model.number="data.limit_num"
              clearable
            ></el-input>
          </el-col>
          <el-col :span="3">&nbsp;张</el-col>
        </el-form-item>

        <el-form-item label="发放总数" prop="full_num">
          <el-col :span="12">
            <el-input
              placeholder
              v-enterNumber
              type="text"
              v-model.number="data.full_num"
              clearable
            ></el-input>
          </el-col>
          <el-col :span="3">&nbsp;张</el-col>
        </el-form-item>

        <el-form-item label="限制某个等级会员才能领取" prop="limit_lv">
          <el-col :span="12">
            <el-select v-model="data.limit_lv" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
        </el-form-item>

        <el-form-item>
          <el-button
            :loading="$store.state.isLoading"
            size="medium"
            type="primary"
            @click.prevent="subForm('data')"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
    <keep-alive>
      <component
        :is="current"
        :show="shows"
        :isAll="true"
        showType="list"
        @sendShop="getSend"
        @isshow="getShow"
      ></component>
    </keep-alive>
  </div>
</template>

<style lang="less" scoped></style>

<script>
import xzShop from "@/components/currency/xz_shop.vue";
import xzusershop from "@/components/currency/xz_usershop.vue";
import xzdriverwork from "@/components/currency/xz_driverwork.vue";
import xzShopCate from "@/components/currency/xz_shopCate1.vue";
export default {
  data() {
    var checkTitle = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("标题不能为空"));
      } else {
        callback();
      }
    };

    return {
      options: [
        {
          value: "",
          label: "",
        },
      ],
      mytitle: "",
      fileList2: [],
      updateUrl: "",
      showImg: true,
      value: "",
      data: {
        title: "",
        money: "",
        cdn_xfm: "",
        cdn_pid: "",
        cdn_sid: "",
        lifetime: "",
        limit_num: "",
        jf_change: "",
        limit_lv: "",
        full_num: "",
        pay_types: "0",
        page_get: "0",
        types: "0",
        cdn_cid: "",
        cdn_cid_cn: [],
      },

      loading: false,
      shows: true,
      shopImg: "",
      shopobj: {},
      current: "",
      dataYZ: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        pay_types: [
          { required: true, message: "请选择红包支付类型", trigger: "blur" },
        ],
        money: [{ required: true, message: "请输入金额", trigger: "blur" }],
        // cdn_xfm:[
        //     { required: true, message: '请输入消费金额', trigger: 'blur' },
        // ],
        //  cdn_pid:[
        //     { required: true, message: '请输入商品ID', trigger: 'blur' },
        // ],
        // cdn_sid:[
        //     { required: true, message: '请输入商家ID', trigger: 'blur' },
        // ],
        // lifetime:[
        //     { required: true, message: '请输入过期时间', trigger: 'blur' },
        // ],
        // limit_num:[
        //     { required: true, message: '请输入限领张数', trigger: 'blur' },
        // ],
        // limit_lv:[
        //     { required: true, message: '请输入限制等级', trigger: 'blur' },
        // ],
        // full_num:[
        //     { required: true, message: '请输入发放总数', trigger: 'blur' },
        // ],
        // jf_change:[
        //     { required: true, message: '请输入积分领取条件', trigger: 'blur' },
        // ],
      },
      visible: this.show,
    };
  },
  components: {
    xzShop,
    xzusershop,
    xzdriverwork,
    xzShopCate,
  },
  props: {
    show: Boolean,
    editId: String,
    clickNum: Number,
  },
  methods: {
    handleCloses(i) {
      this.data.cdn_cid_cn.splice(i, 1);
    },
    handleClose(item, i) {
      var data = this.data.cdn_pid.split(",");
      data.splice(i, 1);
      this.data.cdn_pid = data.join(",");
    },
    xzshop(str) {
      if (str == "xzShop") {
        if (
          this.$store.state.shopSlist == "" ||
          this.$store.state.shopSlist.page != 1
        ) {
          this.$store.dispatch("getShopsAll", { page: 1, page_size: 10 });
        }
      }
      this.current = str;
      this.shows = true;
    },
    getShow(val) {
      this.shows = val;
    },
    getSend(row) {
      console.log(row);
      if (this.current == "xzShop") {
        this.shopobj = row;
        if (row.id == 0) {
          this.data.cdn_pid = row.id;
          this.shopImg = row.piclink;
        } else {
          var data = this.data.cdn_pid.split(",");
          var index = data.findIndex((item, i) => {
            return item == row.id;
          });
          if (index >= 0) {
            return;
          }
          if (this.data.cdn_pid == 0) {
            this.data.cdn_pid = "";
          }
          if (this.data.cdn_pid == "") {
            this.data.cdn_pid = row.id;
          } else {
            this.data.cdn_pid = this.data.cdn_pid + "," + row.id;
          }
        }
      } else if (this.current == "xzShopCate") {
        var data = this.data.cdn_cid_cn;
        var index = data.findIndex((item, i) => {
          return item == row.id;
        });
        if (index >= 0) {
          return;
        }
        this.data.cdn_cid_cn.push({ id: row.id, title: row.title });
      } else if (this.current == "xzdriverwork") {
        this.data.cdn_sid = row.uid;
        this.shopobj = row;
        this.shopImg = row.avatar;
      } else {
        this.data.cdn_sid = row.id;
        this.shopobj = row;
        this.shopImg = row.avatar;
      }

      // this.$emit("sendRow",row)
    },
    uploadSuccess(response, file, fileList) {
      if (response.code == 200 && response.code_desc == "请求成功") {
        this.$message.success("上传成功！");
        if (response.result.indexOf("http") <= 0) {
          this.showImg = true;
          this.data.pic = response.result;
          this.updateUrl = "/api/" + response.result;
        }
      } else if (response.code == 400) {
        this.$message.error("上传失败！不支持的类型");
      }
    },
    uploadError(response) {
      if ((response.code = 400)) {
        this.$message.error("无效请求");
      }
    },
    getOption() {
      var data = {};
      this.$api.getUser.getRatingOption(data).then((res) => {
        if (res.data.code == 200) {
          res.data.result.unshift({ value: "0", label: "应用所有等级" });
          this.options = res.data.result;
        }
      });
    },
    handChange(val) {
      console.log(val);
      this.data.cate = val;
    },

    closeDialog() {
      this.visible = false;
    },
    getDetails(id) {
      var data = {};
      data["id"] = id;
      this.$api.getNews.PacketDetail(data).then((res) => {
        if (res.data.code == 200) {
          // for (var i in res.data.result) {
          //   if (res.data.result[i] == "0") {
          //     res.data.result[i] = "";
          //   }
          //   if (res.data.result.limit_lv == "") {
          //     res.data.result.limit_lv = 0;
          //   }
          // }
          this.data = res.data.result;
          this.data.id = id;
          this.data.cdn_cid_cn = res.data.result.cdn_cid_cn || [];
        }
      });
    },
    subForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.editId == undefined) {
            this.AddNews(formName);
          } else {
            this.UpdateNews(formName);
          }
        }
      });
    },
    AddNews() {
      var params = JSON.parse(JSON.stringify(this.data));
      if (this.data.cdn_cid_cn) {
        var str = "";
        for (var i in this.data.cdn_cid_cn) {
          str += this.data.cdn_cid_cn[i].id + "@";
        }
        str = str.slice(0, -1);

        params.cdn_cid = str;
        delete params.cdn_cid_cn;
      }
      this.$api.getNews.PacketSaveAdd(params).then((res) => {
        if (res.data.status == 1 && res.data.code == 200) {
          this.$fnc.alertSuccess({ text: "添加成功" });
          this.$emit("parent", "这里刷新父页面");
          this.visible = false;
        } else {
          this.$fnc.alertError(res.data.code_desc, res.data.result);
        }
      });
    },
    UpdateNews(formName) {
      console.log("更新中。。");
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var params = JSON.parse(JSON.stringify(this.data));
          if (this.data.cdn_cid_cn) {
            var str = "";
            for (var i in this.data.cdn_cid_cn) {
              str += this.data.cdn_cid_cn[i].id + "@";
            }
            str = str.slice(0, -1);

            params.cdn_cid = str;
            delete params.cdn_cid_cn;
          }
          params.id = this.editId;
          this.$api.getNews.packetSaveEdit(params).then((res) => {
            if (res.data.code == 200 && res.data.result != null) {
              this.$emit("parent", "这里刷新父页面");
              this.$fnc.alertSuccess({ text: "编辑成功" }); //成功弹出框
              this.visible = false;
            } else {
              this.$fnc.alertError(res.data.result); //失败弹出框
            }
          });
        }
      });
    },
  },
  watch: {
    show() {
      console.log(this.show);
      this.visible = this.show;
    },
    clickNum(id) {
      if (this.editId !== undefined) {
        this.mytitle = "红包编辑";
        this.getDetails(this.editId);
      } else {
        this.mytitle = "添加红包";
        if (this.$refs["data"] !== undefined) {
          this.$refs["data"].resetFields();
        }
        this.selectedOptions = [];
        this.updateUrl = "";
        this.showImg = false;
      }
    },
  },
  mounted() {},
  created() {
    this.getOption();
  },
  updated() {},
};
</script>
